package com.jbit.hxy.service.impl;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jbit.hxy.common.Result;
import com.jbit.hxy.model.dto.WxAddressFromDTO;
import com.jbit.hxy.model.po.WxAddress;
import com.jbit.hxy.service.adress.WxAddressService;
import com.jbit.hxy.mapper.WxAddressMapper;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.util.List;

/**
* @author 28575
* @description 针对表【wx_address(地址簿)】的数据库操作Service实现
* @createDate 2024-09-07 11:27:52
*/
@Service
@RequiredArgsConstructor
public class WxAddressServiceImpl extends ServiceImpl<WxAddressMapper, WxAddress>
    implements WxAddressService {
    private final WxAddressMapper wxAddressMapper;

    @Override
    public Result getAddress(Integer userId) {
        List<WxAddress> wxAddresses = wxAddressMapper.selectList(new QueryWrapper<WxAddress>().eq("user_id", userId));
        return Result.success(wxAddresses);
    }

    @Override
    public Result addAddress(WxAddressFromDTO wxAddressFromDTO) {
        WxAddress wxAddress = new WxAddress();
        BeanUtils.copyProperties(wxAddressFromDTO, wxAddress);
        if (wxAddress.getIsDefault() == 1) {
            List<WxAddress> wxAddresses = wxAddressMapper.selectList(null);
            for (WxAddress address : wxAddresses) {
                if (address.getIsDefault() == 1) {
                    address.setIsDefault(0);
                    wxAddressMapper.updateById(address);
                }
            }
        }
        wxAddressMapper.insert(wxAddress);
        return Result.success("添加成功");
    }

    @Override
    public Result updateAddress(WxAddressFromDTO wxAddressFromDTO) {

        WxAddress wxAddress = new WxAddress();
        BeanUtils.copyProperties(wxAddressFromDTO, wxAddress);
        if (wxAddress.getIsDefault() == 1) {
            List<WxAddress> wxAddresses = wxAddressMapper.selectList(null);
            for (WxAddress address : wxAddresses) {
                if (address.getIsDefault() == 1) {
                    address.setIsDefault(0);
                    wxAddressMapper.updateById(address);
                }
            }
        }
        wxAddressMapper.updateById(wxAddress);
        return Result.success("修改成功");
    }

    @Override
    public Result deleteAddress(Integer id) {

        wxAddressMapper.deleteById(id);
        return Result.success("删除成功");
    }

    @Override
    public Result getAddressByUserId(Integer userId) {

        WxAddress wxAddress = wxAddressMapper.selectOne(new QueryWrapper<WxAddress>().eq("user_id", userId).eq("is_default", 1));
        if (wxAddress == null) {
            return Result.fail("没有默认地址");
        }
        return Result.success(wxAddress);
    }
}




